package cn.congine.wizarpos.mall.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.WxAddress;
import cn.congine.wizarpos.mall.model.WxOrderDetail;
import cn.congine.wizarpos.mall.model.open.AddressDetailInput;
import cn.congine.wizarpos.mall.model.open.AddressDetailOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.UpdateOrderInfoInput;
import cn.congine.wizarpos.mall.model.open.UpdateOrderInfoOutput;
import cn.congine.wizarpos.mall.model.open.WechartOrder;
import cn.congine.wizarpos.mall.model.open.WechartOrderDetailInput;
import cn.congine.wizarpos.mall.model.open.WechartOrderOutput;
import cn.congine.wizarpos.mall.model.open.WechartOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.WechartOrderQueryOutput;
import cn.congine.wizarpos.mall.model.open.WxOrderView;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.vo.MyOrderView;
import cn.congine.wizarpos.mall.vo.ProductView;

@Controller
@RequestMapping(value = "/wx_order_detail")
public class WxOrderDetailAction {

	private static Logger logger = Logger.getLogger(WxOrderDetailAction.class);

	@Autowired
	private WPosHttpClient wposHttpClient;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	
	@RequestMapping(value = "/get_order_detail")
	public ModelAndView getWxOrderDetail(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId,
			HttpServletRequest httpRequest) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> urlMap = new HashMap<String, Object>();
		Map<String, Object> priceMap = new HashMap<String, Object>();
		
		WechartOrderDetailInput wechartOrderDetailInput = new WechartOrderDetailInput();
		wechartOrderDetailInput.setMid(mid);
		wechartOrderDetailInput.setOrderId(orderId);
		WechartOrderOutput wechartOrderOutput = (WechartOrderOutput) wizarposOpenRestClient.post(wechartOrderDetailInput, "/order/detail", WechartOrderOutput.class);
		
		WechartOrder order = wechartOrderOutput.getResult();
		
		List<WxOrderDetail> list = order.getOrderDetail();
				
		AddressDetailInput addressDetailInput = new AddressDetailInput();
		addressDetailInput.setMid(mid);
		addressDetailInput.setId(order.getAddressId());
		AddressDetailOutput addressDetailOutput = (AddressDetailOutput) wizarposOpenRestClient.post(addressDetailInput, "/address/detail", AddressDetailOutput.class);
		WxAddress address = addressDetailOutput.getResult();

		for (WxOrderDetail detail : list) {
			String productId = detail.getProductId();
			if (detail.getPicUrl() == null) {
				urlMap.put(productId, SysConstants.DEFAULT_PICTURE);
			} else {
				urlMap.put(productId, Function.dealGridPicUrl(detail.getPicUrl(), 300, 300));
			}
			priceMap.put(productId, Utils.formatAmount(detail.getPrice()));
		}

		String amount = Utils.formatAmount(order.getAmount());

		switch (order.getStatus()) {
		case "0":
			data.put("status", "待付款");
			break;
		case "1":
			data.put("status", "待发货");
			break;
		case "2":
			data.put("status", "待收货");
			break;
		case "3":
			data.put("status", "已收货");
			break;
		case "4":
			data.put("status", "交易成功");
			break;
		case "5":
			data.put("status", "交易取消");
			break;
		default:
			break;
		}

		if (order.getDispatchType() != null) {
			switch (order.getDispatchType()) {
			case "1":
				data.put("type", "货到付款");
				break;
			case "2":
				data.put("type", "微信支付送货上门");
				break;
			case "3":
				data.put("type", " 微信支付到店提货");
				break;
			case "4":
				data.put("type", "会员卡支付送货上门");
				break;
			case "5":
				data.put("type", "会员卡支付到店提货");
				break;
			default:
				break;
			}
		} else {
			data.put("type", "待定");
		}

		switch (order.getPayStatus()) {
		case "0":
			data.put("payStatus", "待付款");
			break;
		case "1":
			data.put("payStatus", "已付款");
			break;
		default:
			break;
		}
//		if (order.getDispatchTime() == null) {
		if (order.getDispatchTime() == 0) {		
			data.put("dispathTime", "暂无信息");
		} else {
			data.put("dispathTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(new Date(order.getDispatchTime())));
		}

		// 用户是否可以确认收货标志
		if ("1".equals(order.getStatus()) 
				|| "2".equals(order.getStatus()) 
				||"3".equals(order.getStatus())) {
			data.put("finishFlag", true);
		}
		// 是否有提货券链接标志
		if (("3".equals(order.getDispatchType()) 
				|| "5".equals(order.getDispatchType()))
				&& order.getSaleOrderId() == null 
				&& "1".equals(order.getPayStatus())) {
			data.put("voucherFlag", true);
		}
		if (!StringUtils.isEmpty(order.getSaleOrderNo()) ) {
			data.put("showSalerNO", Function.getShowSaleOrderNo(order.getSaleOrderNo()));
		} else {
			data.put("showSalerNO", "暂无信息");
		}
		
		
		data.put("amount", amount);
		data.put("price", priceMap);
		data.put("url", urlMap);
		data.put("address", address);
		data.put("list", list);
		data.put("orderId", orderId);
		data.put("mid", mid);
		data.put("showOrderId", Function.getShowWxOrderId(orderId));
		//data.put("showSalerNO", Function.getShowSaleOrderNo(order.getSaleOrderNo()));
		data.put("orderTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date(order.getCreateTime())));
		return new ModelAndView("order/orderdetail", data);
	}
	
	/**
	 * 我的订单列表
	 * 
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/my_order_detail")
	public ModelAndView getMyWxOrderDetail(
			@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> priceMap = new HashMap<String, Object>();
		Map<String, Object> productMap = new HashMap<String, Object>();
		Map<String, Object> priMap = new HashMap<String, Object>();
		Map<String, Object> amountMap = new HashMap<String, Object>();
		Map<String, String> showIdMap = new HashMap<String, String>();
		Map<String, Object> timeMap = new HashMap<String, Object>();

		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		
		logger.info(">>进入我的订单页 mid=" + mid);
		
		//请求开发平台，获取商户信息
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput, "/merchantdef/info", MerchantDefQueryOutput.class);
		MerchantDef merchantDef = merchantDefQueryOutput.getResult();		
		
		//请求开发平台， 通过openId,mid,获得一个月内，三个月内，全部这三个分类的订单
		WechartOrderQueryInput wechartOrderQueryInput = new WechartOrderQueryInput();
		wechartOrderQueryInput.setMid(mid);
		wechartOrderQueryInput.setCardId(cardId);
		wechartOrderQueryInput.setPageNo(1);
		wechartOrderQueryInput.setFlag(1);//一个月内
		WechartOrderQueryOutput wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list", WechartOrderQueryOutput.class);		
		List<WxOrderView> oneMonth = wechartOrderQueryOutput.getWxOrderViewList();
		
		wechartOrderQueryInput.setFlag(2);//三个月内		
		wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list", WechartOrderQueryOutput.class);		
		List<WxOrderView> threeMonth = wechartOrderQueryOutput.getWxOrderViewList();		
		
		wechartOrderQueryInput.setFlag(3);//全部		
		wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list", WechartOrderQueryOutput.class);		
		List<WxOrderView> all = wechartOrderQueryOutput.getWxOrderViewList();		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (WxOrderView wxOrderView : all) {
			if (wxOrderView == null) {
				continue;
			}
			String orderId = wxOrderView.getOrderId();
			showIdMap.put(orderId, Function.getShowWxOrderId(orderId));
			String amount = Utils.formatAmount(wxOrderView.getAmount());
			productMap.put(orderId, wxOrderView.getWxOrderDetail());
			amountMap.put(orderId, amount);
			timeMap.put(orderId, sf.format(new Date(wxOrderView.getCreateTime())));
						
			for (WxOrderDetail orderDetail : wxOrderView.getWxOrderDetail()) {
				priceMap.put(orderDetail.getId(),
						Utils.formatAmount(orderDetail.getPrice()));
				if ("".equals(orderDetail.getPicUrl())) {
					priMap.put(orderDetail.getId(), SysConstants.DEFAULT_PICTURE);					
				} else {
					priMap.put(orderDetail.getId(), Function.dealGridPicUrl(orderDetail.getPicUrl(), 300, 300));
				}
			}
		}		
		
		data.put("showIdMap", showIdMap);
		data.put("amountMap", amountMap);
		data.put("priMap", priMap);
		data.put("productMap", productMap);
		data.put("priceMap", priceMap);
		data.put("timeMap", timeMap);
		data.put("all", all);
		data.put("oneMonth", oneMonth);
		data.put("threeMonth", threeMonth);
		data.put("merchant", merchantDef);
		data.put("mid", mid);
		data.put("cardId", cardId);
		return new ModelAndView("order/orderlist", data);
	}

	/**
	 * 我的所有订单的接下来10条记录
	 * 
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/next4All")
	public @ResponseBody List<MyOrderView> next4All(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cardId") String cardId,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage,
		    HttpServletRequest httpRequest) {

		List<MyOrderView> orderViewList = new ArrayList<MyOrderView>();
		WechartOrderQueryInput wechartOrderQueryInput = new WechartOrderQueryInput();
		wechartOrderQueryInput.setMid(mid);
		wechartOrderQueryInput.setCardId(cardId);
		wechartOrderQueryInput.setPageNo(nextPage);
		wechartOrderQueryInput.setFlag(3);
		WechartOrderQueryOutput wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list",WechartOrderQueryOutput.class);
		List<WxOrderView> next4All = wechartOrderQueryOutput
				.getWxOrderViewList();

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (WxOrderView wxOrderView : next4All) {
			if (wxOrderView == null) {
				continue;
			}
			MyOrderView orderView = new MyOrderView();
			orderView.setOrderId(wxOrderView.getOrderId());
			orderView.setShowOrderId(Function.getShowWxOrderId(wxOrderView.getOrderId()));
			orderView.setAmount(Utils.formatAmount(wxOrderView.getAmount()));
			orderView.setCreateTime(sf.format(new Date(wxOrderView.getCreateTime())));
			List<ProductView> productViewList = new ArrayList<ProductView>();
			orderView.setProducts(productViewList);
			orderView.setDispatchType(wxOrderView.getDispatchType());
			orderView.setPayStatus("0".equals(wxOrderView.getPayStatus()) ? "未付款" : "已付款");
			orderView.setMid(mid);
			switch (wxOrderView.getStatus()) {
			case "0":
				orderView.setStatus("待付款");
				break;
			case "1":
				orderView.setStatus("待发货");
				break;
			case "2":
				orderView.setStatus("待收货");
				break;
			case "3":
				orderView.setStatus("已收货");
				break;
			case "4":
				orderView.setStatus("交易成功");
				break;
			case "5":
				orderView.setStatus("交易取消");
				break;
			default:
				break;
			}
			for (WxOrderDetail orderDetail : wxOrderView.getWxOrderDetail()) {
				ProductView productView = new ProductView();
				productView.setId(orderDetail.getProductId());
				productView.setCode(orderDetail.getCode());
				productView.setName(orderDetail.getProductName());
				productView.setNum(orderDetail.getQty());
				productView.setPrice(Utils.formatAmount(orderDetail.getPrice()));
				if ("".equals(orderDetail.getPicUrl())) {
					productView.setPritrue(SysConstants.DEFAULT_PICTURE);
				} else {
					productView.setPritrue(Function.dealGridPicUrl(orderDetail.getPicUrl(), 150, 150));
				}
				productViewList.add(productView);
			}
			orderViewList.add(orderView);
		}
		return orderViewList;
	}

	/**
	 * 我的所有订单的接下来10条记录
	 * 
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/next4One")
	public @ResponseBody List<MyOrderView> next4One(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cardId") String cardId,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage,
			HttpServletRequest httpRequest) {
		
		List<MyOrderView> orderViewList = new ArrayList<MyOrderView>();
		WechartOrderQueryInput wechartOrderQueryInput = new WechartOrderQueryInput();
		wechartOrderQueryInput.setMid(mid);
		wechartOrderQueryInput.setCardId(cardId);
		wechartOrderQueryInput.setPageNo(nextPage);
		wechartOrderQueryInput.setFlag(1);
		WechartOrderQueryOutput wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list",WechartOrderQueryOutput.class);
		List<WxOrderView> next4All = wechartOrderQueryOutput
				.getWxOrderViewList();

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (WxOrderView wxOrderView : next4All) {
			if (wxOrderView == null) {
				continue;
			}
			MyOrderView orderView = new MyOrderView();
			orderView.setOrderId(wxOrderView.getOrderId());
			orderView.setShowOrderId(Function.getShowWxOrderId(wxOrderView.getOrderId()));
			orderView.setAmount(Utils.formatAmount(wxOrderView.getAmount()));
			orderView.setCreateTime(sf.format(new Date(wxOrderView.getCreateTime())));
			List<ProductView> productViewList = new ArrayList<ProductView>();
			orderView.setProducts(productViewList);
			orderView.setDispatchType(wxOrderView.getDispatchType());
			orderView.setPayStatus("0".equals(wxOrderView.getPayStatus()) ? "未付款" : "已付款");
			orderView.setMid(mid);
			switch (wxOrderView.getStatus()) {
			case "0":
				orderView.setStatus("待付款");
				break;
			case "1":
				orderView.setStatus("待发货");
				break;
			case "2":
				orderView.setStatus("待收货");
				break;
			case "3":
				orderView.setStatus("已收货");
				break;
			case "4":
				orderView.setStatus("交易成功");
				break;
			case "5":
				orderView.setStatus("交易取消");
				break;
			default:
				break;
			}
			for (WxOrderDetail orderDetail : wxOrderView.getWxOrderDetail()) {
				ProductView productView = new ProductView();
				productView.setId(orderDetail.getProductId());
				productView.setCode(orderDetail.getCode());
				productView.setName(orderDetail.getProductName());
				productView.setNum(orderDetail.getQty());
				productView.setPrice(Utils.formatAmount(orderDetail.getPrice()));
				if ("".equals(orderDetail.getPicUrl())) {
					productView.setPritrue(SysConstants.DEFAULT_PICTURE);
				} else {
					productView.setPritrue(Function.dealGridPicUrl(orderDetail.getPicUrl(), 300, 300));
				}
				productViewList.add(productView);
			}
			orderViewList.add(orderView);
		}
		return orderViewList;
	}	

	/**
	 * 我的所有订单的接下来10条记录
	 * 
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/next4Three")
	public @ResponseBody List<MyOrderView> next4Three(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cardId") String cardId,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage,
			HttpServletRequest httpRequest) {

		List<MyOrderView> orderViewList = new ArrayList<MyOrderView>();
		WechartOrderQueryInput wechartOrderQueryInput = new WechartOrderQueryInput();
		wechartOrderQueryInput.setMid(mid);
		wechartOrderQueryInput.setCardId(cardId);
		wechartOrderQueryInput.setPageNo(nextPage);
		wechartOrderQueryInput.setFlag(2);
		WechartOrderQueryOutput wechartOrderQueryOutput = (WechartOrderQueryOutput) wizarposOpenRestClient.post(wechartOrderQueryInput, "/order/list",WechartOrderQueryOutput.class);
		List<WxOrderView> next4All = wechartOrderQueryOutput
				.getWxOrderViewList();

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (WxOrderView wxOrderView : next4All) {
			if (wxOrderView == null) {
				continue;
			}
			MyOrderView orderView = new MyOrderView();
			orderView.setOrderId(wxOrderView.getOrderId());
			orderView.setShowOrderId(Function.getShowWxOrderId(wxOrderView.getOrderId()));
			orderView.setAmount(Utils.formatAmount(wxOrderView.getAmount()));
			orderView.setCreateTime(sf.format(new Date(wxOrderView.getCreateTime())));
			List<ProductView> productViewList = new ArrayList<ProductView>();
			orderView.setProducts(productViewList);
			orderView.setDispatchType(wxOrderView.getDispatchType());
			orderView.setPayStatus("0".equals(wxOrderView.getPayStatus()) ? "未付款" : "已付款");
			orderView.setMid(mid);
			switch (wxOrderView.getStatus()) {
			case "0":
				orderView.setStatus("待付款");
				break;
			case "1":
				orderView.setStatus("待发货");
				break;
			case "2":
				orderView.setStatus("待收货");
				break;
			case "3":
				orderView.setStatus("已收货");
				break;
			case "4":
				orderView.setStatus("交易成功");
				break;
			case "5":
				orderView.setStatus("交易取消");
				break;
			default:
				break;
			}
			for (WxOrderDetail orderDetail : wxOrderView.getWxOrderDetail()) {
				ProductView productView = new ProductView();
				productView.setId(orderDetail.getProductId());
				productView.setCode(orderDetail.getCode());
				productView.setName(orderDetail.getProductName());
				productView.setNum(orderDetail.getQty());
				productView.setPrice(Utils.formatAmount(orderDetail.getPrice()));
				if ("".equals(orderDetail.getPicUrl())) {
					productView.setPritrue(SysConstants.DEFAULT_PICTURE);
				} else {
					productView.setPritrue(Function.dealGridPicUrl(orderDetail.getPicUrl(), 300, 300));
				}
				productViewList.add(productView);
			}
			orderViewList.add(orderView);
		}
		return orderViewList;
	}	
	
	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "/del_order")
	@ResponseBody
	public RespMessage delWxOrder(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId,
			HttpServletRequest httpRequest) {	
		RespMessage res = new RespMessage();
				
		UpdateOrderInfoInput input = new UpdateOrderInfoInput();
		input.setMid(mid);
		input.setStatus("5");
		input.setOrderId(orderId);
		UpdateOrderInfoOutput output = (UpdateOrderInfoOutput) wizarposOpenRestClient.post(input, "/order/update_orderinfo",UpdateOrderInfoOutput.class);
		if (output != null && "0".equals(output.getCode())) {//0操作成功
			res.setCode(0);
			return res;
		} else {//其它，操作失败
			res.setCode(1);
			res.setMessage(output.getMessage());
			return res;
		}
	}
	
	/**
	 * 确认收货
	 * 
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "/finish_order")
	@ResponseBody
	public RespMessage finishWxOrder(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId,
			HttpServletRequest httpRequest) {	
		RespMessage res = new RespMessage();
		
		UpdateOrderInfoInput input = new UpdateOrderInfoInput();
		input.setMid(mid);
		input.setStatus("4");
		input.setOrderId(orderId);
		UpdateOrderInfoOutput output = (UpdateOrderInfoOutput) wizarposOpenRestClient.post(input, "/order/update_orderinfo",UpdateOrderInfoOutput.class);		
		if (output != null && "0".equals(output.getCode())) {//0操作成功
			res.setCode(0);
			return res;
		} else {//其它，操作失败
			res.setCode(1);
			res.setMessage(output.getMessage());
			return res;
		}
	}	
}
